package dsk.demo.product.controller.product;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import dsk.demo.common.utils.R;
import dsk.demo.product.entity.ProductCarEntity;
import dsk.demo.product.entity.ProductEntity;
import dsk.demo.product.service.ProductCarService;
import dsk.demo.product.service.ProductService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author daishikun
 * @email 940798525@qq.com
 * @date 2022-09-17 09:09:41
 */
@RestController
@RequestMapping("product/productcar")
public class ProductCarController {
    @Autowired
    private ProductCarService productCarService;

    @Autowired
    private ProductService productService;


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("product:productcar:info")
    public R info(@PathVariable("id") Long id) {
        ProductCarEntity productCar = productCarService.getById(id);

        return R.ok().put("productCar", productCar);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("product:productcar:save")
    public R save(@RequestBody ProductCarEntity productCar) {
        productCar.setProductNo(productCar.getProductNo().trim());
        productCarService.saveOrUpdate(productCar);
        return R.ok();
    }

    /**
     * 保存
     */
    @RequestMapping("/saveAll")
    @RequiresPermissions("product:productcar:save")
    public R saveAll(@RequestBody ProductCarEntity[] productCarList) {
        for (ProductCarEntity productCar : productCarList) {
            productCar.setProductNo(productCar.getProductNo().trim());
        }
        Set<ProductCarEntity> collect = Arrays.stream(productCarList).collect(Collectors.toSet());
        productCarService.insertBatch(collect);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("product:productcar:update")
    public R update(@RequestBody ProductCarEntity productCar) {
        productCar.setProductNo(productCar.getProductNo().trim());
        productCarService.updateById(productCar);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("product:productcar:delete")
    public R delete(@RequestBody Long[] ids) {
        productCarService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 批量上传  所需的模板下载
     */
    @RequestMapping("/downloadTemp")
    public void downloadTemp(HttpServletResponse response) throws IOException {
        // 通过工具类创建writer，默认创建xls格式
        ExcelWriter writer = ExcelUtil.getWriter();
        //配置别名
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        map.put("productNo", "本厂编号");
        map.put("brand", "品牌");
        map.put("fullname", "车型全名");
        writer.setHeaderAlias(map);
        //只写入配置了别名的属性
        writer.setOnlyAlias(true);

        ProductCarEntity productCarEntity = new ProductCarEntity();
        List<ProductCarEntity> rows = new ArrayList<>();
        rows.add(productCarEntity);
        // 一次性写出内容，使用默认样式，强制输出标题
        writer.write(rows, true);
        //out为OutputStream，需要写出到的目标流

        //response为HttpServletResponse对象
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        response.setHeader("Content-Disposition", "attachment;filename=tempcar.xls");
        ServletOutputStream out = response.getOutputStream();

        writer.flush(out, true);
        // 关闭writer，释放内存
        writer.close();
        //此处记得关闭输出Servlet流
        IoUtil.close(out);
    }

    /**
     * excel批量上传
     */
    @RequestMapping("/saveList")
    public R saveList(MultipartFile file) {
        try {
            List<ProductCarEntity> productCarEntities = productCarService.excel2ProductEntityList(file);
            //补齐查询号码
            for (ProductCarEntity entity : productCarEntities) {
                entity.setProductNo(entity.getProductNo().trim());
            }
            //先查询所有本厂编号,不存在的本厂编号应该剔除
            List<String> productNos = productCarEntities.stream().map(item -> {
                return item.getProductNo();
            }).collect(Collectors.toList());
            List<ProductEntity> productEntities = productService.queryByProductNos(productNos);
            Set<ProductCarEntity> collect = productCarEntities.stream().filter(item -> {
                return productNos.indexOf(item.getProductNo()) >= 0;
            }).collect(Collectors.toSet());

            productCarService.insertBatch(collect);
            return R.ok("批量导入成功");
        } catch (Exception e) {
            System.out.println(e);
            return R.error(501, "上传失败");
        }
    }

}
